/*
 * @Descripttion:
 * @Author: zhanyi
 * @Date: 2021-10-10 16:58:35
 * @FilePath: \wczd-ui\src\store\modules\permission.js
 */
import { getRouters } from '@/api/menu'

const permission = {
  state: {
    routes: [],
    addRoutes: [],
    father_route: '/system',
    page_info: ''
  },
  mutations: {
    SET_FATHER_ROUTE: (state, route) => {
      state.father_route = route
      localStorage.setItem('father_route', route)
    },
    SET_ROUTES: (state, routes) => {
      state.addRoutes = routes
      routes = routes.filter(item => item.path === (localStorage.getItem('father_route') || state.father_route))[0]
      if (routes.meta) {
        state.page_info = routes.meta
      }
      state.routes = routes.children
    }
  },
  actions: {
    changeFatherRoute({ commit }, data) {
      commit('SET_FATHER_ROUTE', data)
      commit('SET_ROUTES', this.state.permission.addRoutes)
    },
    // 生成路由
    GenerateRoutes({ commit }) {
      return new Promise(resolve => {
        // 向后端请求路由数据
        getRouters().then(res => {
          const accessedRoutes = filterAsyncRouter(res.data)
          accessedRoutes.push({ path: '*', redirect: '/', hidden: true })
          var isb = false
          accessedRoutes.forEach(item => {
            item?.children?.forEach(element => {
              element.path = item.path + '/' + element.path
            })
            // 如果此页面存在，则回到当前模块
            if (localStorage.getItem('father_route') === item.path) {
              isb = true
              commit('SET_FATHER_ROUTE', item.path)
            }
          })
          // 如果此页面不存在，则打开第一个模块
          if (!isb) {
            commit('SET_FATHER_ROUTE', accessedRoutes[0].path)
          }
          commit('SET_ROUTES', accessedRoutes)
          resolve(accessedRoutes)
        })
      })
    }
  }
}

// 遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouter(asyncRouterMap) {
  return asyncRouterMap.filter(route => {
    if (route.children != null && route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children)
    }
    return true
  })
}

export default permission
